package com.yc.vote.servlet;

import com.yc.common.bean.Result;
import com.yc.common.biz.BizException;
import com.yc.common.servlet.BaseServlet;
import com.yc.vote.entity.Record;
import com.yc.vote.entity.User;
import com.yc.vote.service.impl.RecordServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/record/*")
public class RecordServlet extends BaseServlet {

    private RecordServiceImpl biz = new RecordServiceImpl();

    public Result commit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String vid = request.getParameter("vid");
        String[] iids = request.getParameterValues("iid");
        Object o = request.getSession().getAttribute("loginedUser");
        User user = (User) o;
        if(user == null){
            // 未登录
            return Result.failure("请先登录系统",null);
            // TODO 后续完成登录之后, 再屏蔽下面的代码
//            user = new User();
//            user.setId(1);
        }
        List<Record> records = new ArrayList<>();
        if(iids!=null){
            for (String iid : iids) {
                Record record = new Record();
                record.setVid(Integer.parseInt(vid));
                record.setIid(Integer.parseInt(iid));
                record.setUsid(user.getId());
                records.add(record);
            }
        }
        try {
            biz.commit(records);
            return Result.success("投票成功!",null);
        } catch (BizException e) {
            e.printStackTrace();
            return Result.failure(e.getMessage(),null);
        }
    }
}
